import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:internet_file/internet_file.dart';
import 'package:pdfx/pdfx.dart';
import 'package:provider/provider.dart';
import 'dart:async';
import 'dart:typed_data';
import 'package:http/http.dart' as http;

import '../utils/utils.dart';

class PDFPage extends StatefulWidget {
  // final Map parameter;
  // PDFPage(this.parameter);

  @override
  _PDFPage createState() => _PDFPage();
}

class _PDFPage extends State<PDFPage> {
  // keydown监听器
  int _currentIndex = 0;
  late PdfController pdfController;
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _currentIndex = 0;
    // pdfController = PdfController(
    //   // document:_getPDF()
    //   document: PdfDocument.openData(InternetFile.get(url))
    // );
    // _initPDFController();
    _loadPDF();
  }

  /// 异步加载PDF数据并初始化控制器
  Future<void> _loadPDF() async {
    try {
      final Uint8List pdfData = await _fetchPDFData(); // 获取PDF字节数据
      pdfController = PdfController(
        document: PdfDocument.openData(pdfData),
      );
      pdfController.document.then((_) {
        if (mounted) {
          setState(() {
            _isLoading = false; // 加载完成
            _currentIndex = 3;
          });
        }
      });
    } catch (e) {
      print('PDF加载失败: $e');
      setState(() {
        _isLoading = false;
        _currentIndex = 2;
      });
    }
  }

  Future<Uint8List> _fetchPDFData() async {
    final httpClient = http.Client();
    try {
      // final response = await httpClient.post(
      //   Uri.parse('http://192.168.8.130:30800/api/PDF/GetPDF_log'),
      //   body: {
      //     'materialNo': '24764A10006AAE',
      //     'materialVer': '00',
      //     'lotNo': 'B-1010240642-2',
      //     'targetFile': '',
      //     'logtype': '仓库查看',
      //     'orderNo': '1123123213',
      //     'projectNo': 'B-1018248642-2',
      //   },
      // );
      final response = await httpClient.get(Uri.parse(
          'https://zjj.sz.gov.cn/attachment/1/1595/1595106/12236492.pdf'));
      if (response.statusCode == 200) {
        return response.bodyBytes;
      } else {
        throw Exception('Request error:${response.statusCode}');
      }
    } finally {
      httpClient.close();
    }
  }

  Future<void> _initPDFController() async {
    String url = 'https://zjj.sz.gov.cn/attachment/1/1595/1595106/12236492.pdf';
    final pdfData = await InternetFile.get(url);
    pdfController = PdfController(document: PdfDocument.openData(pdfData));
    setState(() {});
  }

  @override
  void dispose() {
    super.dispose();
    pdfController.dispose();
    _currentIndex = 0;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('PDF文档'),
        ),
        body: _currentIndex == 3
            ? const Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    CircularProgressIndicator(),
                    SizedBox(height: 16),
                    Text('加载中...'),
                  ],
                ),
              )
            : PdfView(controller: pdfController)
        // : Text("Test")
        );
  }
}
